package main

import (
	"encoding/json"
	"jlpay-sdk-go/pkg/jlpay/demo"
	"jlpay-sdk-go/pkg/jlpay/models"
	"jlpay-sdk-go/pkg/jlpay/services"
	"jlpay-sdk-go/pkg/jlpay/utils"
)

// 常量定义 - 产品类型
const (
	// 产品类型常量
	ProductTypeQRCode   = "01" // 扫码商户：适用于码牌类商户，支持微信/支付宝/银联二维码交易
	ProductTypeStandard = "02" // 标准商户：适用于POS类商户，支持银行卡+微信/支付宝/银联二维码交易
	ProductTypeScene    = "03" // 场景商户：特定准入商户标准,以人工申请结果为准
	ProductTypeSaaS     = "04" // SaaS商户：适用于SaaS类商户，支持微信/支付宝/银联二维码/银行卡交易

	// 签约模式常量
	SignModePaper      = "P" // 线下纸质协议
	SignModeElectronic = "E" // 电子签章协议
	SignModeJLPay      = "J" // 嘉联电子协议

	// 联系人类型常量
	ContactTypeLegalPerson = "65" // 经营者/法人
	ContactTypeOperator    = "66" // 经办人（经商户授权办理支付业务的人员）

	// 商户身份类型常量
	MerchTypeMicro      = "0" // 小微
	MerchTypeEnterprise = "1" // 营业执照、政府机关、事业单位或其他组织

	// 结算类型常量
	SettleTypeLegalPersonCard   = "01" // 打款至法人银行卡
	SettleTypePublicAccount     = "02" // 打款至对公账户
	SettleTypePrivateAuthorized = "03" // 对私授权收款，打款至他人银行卡
	SettleTypePublicAuthorized  = "04" // 对公授权收款，打款至他人对公账户

	// 结算关系常量
	SettleRelationShareholders     = "01" // 股东/雇佣
	SettleRelationBranches         = "02" // 总分公司
	SettleRelationParentSubsidiary = "03" // 母子公司
	SettleRelationOther            = "09" // 其它
)

// 全局变量，用于存储当前使用的apply_id
var currentApplyID string

// 构建费率信息条目
func buildRateInfo(feeCalcType, rate string, minAmt, maxAmt, fixed, bottom, top, step, baseAmount, baseFee string) map[string]string {
	return map[string]string{
		"fee_calc_type": feeCalcType,
		"rate":          rate,
		"min_amt":       minAmt,
		"max_amt":       maxAmt,
		"fixed":         fixed,
		"bottom":        bottom,
		"top":           top,
		"step":          step,
		"base_amount":   baseAmount,
		"base_fee":      baseFee,
	}
}

// 构建商户基础信息
func buildBaseInfo(isModify bool) map[string]interface{} {

	baseInfo := map[string]interface{}{
		"apply_id":            "1vzougr30f9vcw1754444407235ae93",
		"product_type":        ProductTypeSaaS,
		"sign_mode":           SignModeElectronic,
		"delegatee_sign_mode": SignModeElectronic,
		"agreement_pic":       "jlpay-test/managefile/2024/02/28/1709081506952_af4f376e39d64abeb5dfb8a0c6db0da7.png",
		"agent_id":            "50720711",
		"qrcode_term_auto":    "1",
		"contact_info": map[string]string{
			"contact_type":  ContactTypeLegalPerson,
			"contact_name":  "张三",                   // 敏感字段
			"contact_phone": "13800138000",          // 敏感字段
			"contact_id_no": "110101199003077758",   // 敏感字段，使用正确的身份证号码格式
			"contact_email": "zhangsan@example.com", // 非敏感字段
		},
	}
	return baseInfo
}

// 构建商户身份信息
func buildIdentificationInfo() map[string]interface{} {
	identificationInfo := map[string]interface{}{
		"merch_type": MerchTypeEnterprise,
		"license_info": map[string]string{
			"license_type":   "02",                 // 企业
			"license_name":   "测试科技有限公司",           // 非敏感字段
			"license_no":     "91330108MABTT5NP6U", // 非敏感字段
			"period_begin":   "2024-01-01",
			"period_end":     "2030-01-01",
			"license_pic":    "jlpay-test/managefile/2024/02/28/1709081506952_af4f376e39d64abeb5dfb8a0c6db0da7.png",
			"business_scope": "经营范围",
		},
		"identity_info": map[string]string{
			"id_doc_type":        "01",                 // 身份证
			"id_card_name":       "张三",                 // 敏感字段
			"id_card_no":         "110101199003077758", // 敏感字段
			"legal_person_phone": "13800138000",        // 敏感字段
			"card_period_begin":  "2024-01-01",
			"card_period_end":    "2030-01-01",
			"id_card_address":    "北京市朝阳区测试路123号", // 敏感字段
			"id_card_copy":       "jlpay-test/managefile/2024/02/28/1709081474283_7ddfb60f42d94f8094ec88d7c78ec4a3.png",
			"id_card_national":   "jlpay-test/managefile/2024/02/28/1709081506952_af4f376e39d64abeb5dfb8a0c6db0da7.png",
		},
	}
	return identificationInfo
}

// 构建商户经营信息
func buildBusinessInfo() map[string]string {
	businessInfo := map[string]string{
		"merch_shortname": "商户经营名称",
		"mcc_code":        "5311",
		"address_code":    "440305",
		"address_detail":  "深圳市南山区工业一路22501号",
		"door_pic":        "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
		"indoor_pic":      "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
		"cashier_pic":     "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
	}
	return businessInfo
}

// 构建商户结算账户信息
func buildSettlementInfo() map[string]interface{} {
	settlementInfo := map[string]interface{}{
		"settle_type":     SettleTypeLegalPersonCard,
		"settle_relation": SettleRelationBranches,
		"account_info": map[string]string{
			"account_no":       "6227001215950896532", // 敏感字段
			"account_name":     "张三",                  // 敏感字段
			"cert_type":        "01",                  // 身份证
			"bank_code":        "082",
			"bank_branch_id":   "105584000370",
			"bank_branch_name": "中国建设银行股份有限公司深圳罗湖支行",
			"bank_set_phone":   "13800138000", // 敏感字段
			"account_pic":      "jlpay-test/managefile/2024/02/28/1709106666879_6c53af86b9654680a727b92795dce6c2.jpg",
		},
		"other_info": map[string]string{
			"identity_face_pic": "jlpay-test/managefile/2024/02/28/1709106666879_6c53af86b9654680a727b92795dce6c2.jpg",
		},
	}
	return settlementInfo
}

// 构建商户结算规则和费率规则
func buildSettlementRule() map[string]interface{} {
	// 费率信息列表
	rateInfoList := []map[string]string{
		// 微信支付宝相关费率
		buildRateInfo("30", "0.38", "0", "-1", "0", "0", "-1", "0", "0", "0"),     // 微信
		buildRateInfo("31", "0.38", "0", "-1", "0", "0", "-1", "0", "0", "0"),     // 支付宝
		buildRateInfo("03", "0.38", "0", "100000", "0", "0", "-1", "0", "0", "0"), // 银联二维码

		// 银联内卡费率
		buildRateInfo("01", "0.45", "0", "-1", "0", "0", "1900", "0", "0", "0"), // 银联内卡借记卡 (封顶19元)
		buildRateInfo("02", "0.55", "0", "-1", "0", "0", "-1", "0", "0", "0"),   // 银联内卡贷记卡 (不封顶)

		// 银联外卡费率
		buildRateInfo("11", "0.45", "0", "-1", "0", "0", "1900", "0", "0", "0"), // 银联外卡借记卡
		buildRateInfo("12", "0.55", "0", "-1", "0", "0", "-1", "0", "0", "0"),   // 银联外卡贷记卡

		// 外币支付相关费率
		buildRateInfo("20", "0.60", "0", "-1", "0", "0", "-1", "0", "0", "0"), // 外币DCC
		buildRateInfo("21", "0.60", "0", "-1", "0", "0", "-1", "0", "0", "0"), // 外币EDC
		buildRateInfo("22", "0.60", "0", "-1", "0", "0", "-1", "0", "0", "0"), // 外币EDC-VM
		buildRateInfo("23", "0.55", "0", "-1", "0", "0", "-1", "0", "0", "0"), // 外币EDC优惠-VM

		// 支付宝优享相关费率
		buildRateInfo("34", "0.38", "0", "-1", "0", "0", "1900", "0", "0", "0"), // 支付宝优享借记卡
		buildRateInfo("35", "0.40", "0", "-1", "0", "0", "-1", "0", "0", "0"),   // 支付宝优享贷记卡

		// 万事网联相关费率
		buildRateInfo("60", "0.38", "0", "-1", "0", "0", "1900", "0", "0", "0"), // 万事网联非接优惠
		buildRateInfo("61", "0.45", "0", "-1", "0", "0", "1900", "0", "0", "0"), // 万事网联借记卡
		buildRateInfo("62", "0.55", "0", "-1", "0", "0", "-1", "0", "0", "0"),   // 万事网联贷记卡

		// 快速提现费率
		buildRateInfo("T0", "0.10", "0", "-1", "0", "100", "-1", "0", "0", "0"), // 快速提现 (保底1元)
	}

	settlementRule := map[string]interface{}{
		"settle_info": map[string]string{
			"settle_mode":         "7",      // 仅D1，资金在交易完成第二个自然日结算
			"day_cut":             "000000", // 账单日切点为昨天0点到今天0点
			"settle_session":      "040000", // 4点付款
			"account_change_flag": "0",      // 不允许商户后台变更结算账户
		},
		"rate_info": rateInfoList,
	}
	return settlementRule
}

// 构建其他附加信息
func buildAdditionalInfo() map[string]interface{} {
	additionalInfo := map[string]interface{}{
		"report_info": map[string]string{
			// 可按需添加以下字段
			// "wechat_jsapi_path": "https://xxx.com/pay/",
			// "wechat_sub_appid": "wx1234567890",
			// "wechat_pid": "12345678",
			// "alipay_pid": "12345678",
		},
		// 添加补充信息
		"email":                   "service@example.com", // 非敏感字段
		"contact_address":         "北京市朝阳区测试路123号",       // 非敏感字段
		"emergency_contact_name":  "李四",                  // 非敏感字段
		"emergency_contact_phone": "13900139000",         // 非敏感字段
	}
	return additionalInfo
}

// 构建短信配置
func buildSmsConfig() map[string]string {
	smsConfig := map[string]string{
		// 可按需添加以下字段
		// "merch_login_notify": "1",
		// "withdraw_password_notify": "1",
		// "sign_notify": "1",
		// "realname_notify": "1",
	}
	return smsConfig
}

// 构建商户业务功能配置
func buildFuncInfo() map[string]interface{} {
	funcInfo := map[string]interface{}{
		// 可按需添加以下字段
		// "open_functions": []string{"01", "02"},
	}
	return funcInfo
}

// 商户进件修改示例
func merchantIncomingModifyDemo(merchantService *services.MerchantService) {
	utils.Info("开始执行商户进件修改示例")

	// 创建商户进件修改请求
	request := models.NewMerchantIncomingModifyRequest()

	// 可以覆盖部分信息进行修改
	businessInfo := buildBusinessInfo()
	businessInfo["merch_shortname"] = "深圳市泰思便利店" // 修改商户名称

	requestMap := map[string]interface{}{
		"base_info":           buildBaseInfo(true),
		"identification_info": buildIdentificationInfo(),
		"business_info":       businessInfo,
		"settlement_info":     buildSettlementInfo(),
		"settlement_rule":     buildSettlementRule(),
		"additional_info":     buildAdditionalInfo(),
		"sms_config":          buildSmsConfig(),
		"func_info":           buildFuncInfo(),
	}

	// 设置原始请求数据
	request.SetRawRequestMap(requestMap)

	// 序列化请求数据并打印
	requestJSON, _ := json.Marshal(requestMap)
	utils.Debugf("商户进件修改请求数据: %s", string(requestJSON))

	// 发送请求
	response, err := merchantService.MerchantIncomingModify(request)
	if err != nil {
		utils.Errorf("商户进件修改请求失败: %v", err)
		return
	}

	// 处理响应 - 使用BaseResponse接口的HandleResponse方法
	response.HandleResponse("商户进件修改")

	utils.Info("商户进件修改示例执行完毕")
}

func main() {
	// 设置日志级别为info，显示详细的调试信息
	utils.SetLogLevel("info")

	utils.Info("=============================")
	utils.Info("===== 商户进件修改示例 开始 =====")
	utils.Info("=============================")

	// 创建配置对象和商户服务
	config := demo.CreateDemoConfig()
	merchantService := services.NewMerchantService(config)

	merchantIncomingModifyDemo(merchantService)

	utils.Info("\n=============================")
	utils.Info("===== 商户进件修改示例执行完毕 =====")
	utils.Info("=============================")
}
